package com.sgcc.nfc.lock.presentation.rooms

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Region
import com.sgcc.nfc.lock.domain.model.RoleType
import com.sgcc.nfc.lock.domain.model.UserProfile
import com.sgcc.nfc.lock.domain.repository.RoomRepository
import com.sgcc.nfc.lock.domain.usecase.CreateRoomUseCase
import com.sgcc.nfc.lock.domain.usecase.GetRegionTreeUseCase
import com.sgcc.nfc.lock.domain.usecase.GetRoomDetailUseCase
import com.sgcc.nfc.lock.domain.usecase.UpdateRoomUseCase
import com.sgcc.nfc.lock.domain.usecase.GetProfileUseCase
import com.sgcc.nfc.lock.presentation.common.EventFlow
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch

@HiltViewModel
class RoomFormViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val getRegionTreeUseCase: GetRegionTreeUseCase,
    private val getProfileUseCase: GetProfileUseCase,
    private val createRoomUseCase: CreateRoomUseCase,
    private val updateRoomUseCase: UpdateRoomUseCase,
    private val getRoomDetailUseCase: GetRoomDetailUseCase
) : ViewModel() {

    private val roomId: Long? = savedStateHandle.get<Long>(KEY_ROOM_ID)

    private val _uiState = MutableLiveData(RoomFormUiState())
    val uiState: LiveData<RoomFormUiState> = _uiState

    private val _events = EventFlow<RoomFormEvent>()
    val events = _events.events

    val isEdit: Boolean get() = roomId != null

    private var currentUser: UserProfile? = null
    private var currentUserLoaded = false

    init {
        println("RoomFormViewModel: 初始化 - roomId=$roomId")
        loadInitialData()
    }

    private fun loadInitialData() {
        println("RoomFormViewModel: 加载初始数据")
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            try {
                // 加载用户信息
                ensureCurrentUser()
                
                // 加载区域树
                when (val regionResult = getRegionTreeUseCase()) {
                    is NetworkResult.Success -> {
                        val filteredRegions = applyAccessControl(regionResult.data)
                        
                        // 如果是编辑模式，加载房间详情
                        if (isEdit && roomId != null) {
                            when (val roomResult = getRoomDetailUseCase(roomId)) {
                                is NetworkResult.Success -> {
                                    _uiState.update { 
                                        it.copy(
                                            isLoading = false, 
                                            regions = filteredRegions,
                                            room = roomResult.data,
                                            error = null
                                        ) 
                                    }
                                }
                                is NetworkResult.Error -> {
                                    _uiState.update { 
                                        it.copy(
                                            isLoading = false, 
                                            regions = filteredRegions,
                                            error = roomResult.message
                                        ) 
                                    }
                                }
                                is NetworkResult.Loading -> {
                                    // Loading state already handled
                                }
                            }
                        } else {
                            _uiState.update { 
                                it.copy(
                                    isLoading = false, 
                                    regions = filteredRegions,
                                    error = null
                                ) 
                            }
                        }
                    }
                    is NetworkResult.Error -> {
                        _uiState.update { 
                            it.copy(
                                isLoading = false, 
                                regions = emptyList(),
                                error = regionResult.message ?: "加载区域数据失败"
                            ) 
                        }
                    }
                    is NetworkResult.Loading -> {
                        // Loading state already handled
                    }
                }
            } catch (e: Exception) {
                println("RoomFormViewModel: 加载数据异常 - ${e.message}")
                _uiState.update { 
                    it.copy(
                        isLoading = false, 
                        regions = emptyList(),
                        error = "加载数据失败: ${e.message}"
                    ) 
                }
            }
        }
    }

    fun createRoom(params: RoomRepository.CreateRoomParams) {
        println("RoomFormViewModel: 创建房间 - params=$params")
        viewModelScope.launch {
            _uiState.update { it.copy(isSubmitting = true, error = null) }
            
            try {
                when (val result = createRoomUseCase(params)) {
                    is NetworkResult.Success -> {
                        _uiState.update { it.copy(isSubmitting = false) }
                        _events.emit(RoomFormEvent.SubmitSuccess(RoomFormEvent.OperationType.CREATE))
                    }
                    is NetworkResult.Error -> {
                        _uiState.update { 
                            it.copy(
                                isSubmitting = false, 
                                error = result.message ?: "创建配电房失败"
                            ) 
                        }
                    }
                    is NetworkResult.Loading -> {
                        // Loading state already handled
                    }
                }
            } catch (e: Exception) {
                println("RoomFormViewModel: 创建房间异常 - ${e.message}")
                _uiState.update { 
                    it.copy(
                        isSubmitting = false, 
                        error = "创建配电房失败: ${e.message}"
                    ) 
                }
            }
        }
    }

    fun updateRoom(params: RoomRepository.UpdateRoomParams) {
        println("RoomFormViewModel: 更新房间 - params=$params")
        viewModelScope.launch {
            _uiState.update { it.copy(isSubmitting = true, error = null) }
            
            try {
                when (val result = updateRoomUseCase(params)) {
                    is NetworkResult.Success -> {
                        _uiState.update { it.copy(isSubmitting = false) }
                        _events.emit(RoomFormEvent.SubmitSuccess(RoomFormEvent.OperationType.UPDATE))
                    }
                    is NetworkResult.Error -> {
                        _uiState.update { 
                            it.copy(
                                isSubmitting = false, 
                                error = result.message ?: "更新配电房失败"
                            ) 
                        }
                    }
                    is NetworkResult.Loading -> {
                        // Loading state already handled
                    }
                }
            } catch (e: Exception) {
                println("RoomFormViewModel: 更新房间异常 - ${e.message}")
                _uiState.update { 
                    it.copy(
                        isSubmitting = false, 
                        error = "更新配电房失败: ${e.message}"
                    ) 
                }
            }
        }
    }

    fun currentRegions(): List<Region> = _uiState.value?.regions.orEmpty()

    private inline fun MutableLiveData<RoomFormUiState>.update(transform: (RoomFormUiState) -> RoomFormUiState) {
        val current = value ?: RoomFormUiState()
        value = transform(current)
    }

    private suspend fun ensureCurrentUser() {
        println("RoomFormViewModel: 确保当前用户")
        if (currentUserLoaded) return
        currentUser = null
        currentUserLoaded = true
    }

    private fun applyAccessControl(tree: List<Region>): List<Region> {
        val role = RoleType.fromValue(currentUser?.roleType)
        if (role == null || role == RoleType.SUPER_ADMIN) {
            return tree
        }
        val userRegionId = currentUser?.regionId ?: return tree
        val target = findRegionRecursive(tree, userRegionId) ?: return tree
        return listOf(target)
    }

    private fun findRegionRecursive(regions: List<Region>, targetId: Long): Region? {
        regions.forEach { region ->
            if (region.regionId == targetId) return region
            val match = findRegionRecursive(region.children, targetId)
            if (match != null) return match
        }
        return null
    }

    companion object {
        const val KEY_ROOM_ID = "roomId"
    }
}
